package org.toycode.solr.extractor.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.solr.common.SolrInputDocument;
import org.toycode.solr.config.Prop;
import org.toycode.solr.extractor.PropertyExtractor;

/**
 * This implementations of the interface {@linkplain PropertyExtractor}
 * provides the content extraction for the type <em>text</em> and
 * <em>texts</em> in config.xml.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.2, Aug 26, 2009
 */
final public class TextFileExtractor implements PropertyExtractor {

    private final List<String> EXTRACTABLE_TYPES = Arrays.asList("text",
                                                                 "texts");

    @SuppressWarnings("unchecked")
    public void process(final Prop prop, final Object value,
                        final SolrInputDocument solrInputDocument) {
        final String type = prop.type;
        if (type.equals(EXTRACTABLE_TYPES.get(0))) {
            final String content = readText((String) value);
            solrInputDocument.addField("text_content", content);
        } else if (type.equals(EXTRACTABLE_TYPES.get(1))) {
            final List<String> contents = new ArrayList<String>();
            for (final String path : ((Collection<String>) value)) {
                contents.add(readText(path));
            }
            solrInputDocument.addField("text_content", contents);
        }
    }

    private static String readText(final String path) {
        try {
            final Scanner scanner = new Scanner(new File(path), "UTF-8");
            final StringBuilder sb = new StringBuilder();
            while (scanner.hasNextLine()) {
                sb.append(scanner.nextLine() + "\r\n");
            }

            return sb.toString();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TextFileExtractor.class.getName()).
                    log(Level.SEVERE, null, ex);
        }

        return null;
    }

    public List<String> getExtractableTypes() {
        return EXTRACTABLE_TYPES;
    }
}
